#pragma once
#include <iostream>
#include <string>
#include <filesystem> //c++17
#include <sstream>
#include <fstream>
#include "Mutex.hpp"
#include <cstdio>
#include <memory>
#include <unistd.h>
#include <ctime>


const std::string sgap = "\r\n";

namespace LogModule
{
    using namespace MutexModule;
    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string& message) = 0;
    };

    //控制台刷新方式
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy(){}

        virtual void SyncLog(const std::string& message) override
        {
            LockGuard lockguard(_mutex);    //借助RAll的思路，构造的时候加锁，函数声明周期结束时，析构时自动解锁，避免内存泄漏
            std::cout << message << sgap;
        }
        
        ~ConsoleLogStrategy(){}

    private:
        Mutex _mutex;
    };

    const std::string DefaultPath = "./log";
    const std::string DefaultFileName = "test.Log";

    //文件刷新方式
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string& path = DefaultPath, const std::string& file = DefaultFileName)
            :_path(path),
            _file(file)
        {
            
        }
        virtual void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_mutex);
            _filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            FILE* fp = fopen(_filename.c_str(),"a");
            char buffer[128];

            fwrite(buffer,sizeof(buffer),1,fp);      
            
            fclose(fp);
        }

        ~FileLogStrategy(){}
    private:
        Mutex _mutex;
        std::string _path;
        std::string _file;
        std::string _filename;
    };

    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARRING,
        ERROR,
        FATAL
    };

    std::string LevelToStr(LogLevel level)
    {
        switch(level)
        {
            case LogLevel::DEBUG:
                return "DEBUG"; 
            case LogLevel::INFO:
                return "INFO";
            case LogLevel::ERROR:
                return "ERROR";
            case LogLevel::FATAL:
                return "FATAL";
            case LogLevel::WARRING:
                return "WARRING";
            default:
                return "UNKNOWN";
        }                   
    }

    std::string GetTimeStamp()
    {
        time_t ccur = time(nullptr);//获取时间戳，从1970年1月1日开始
        tm cur_time;//对于c++而言，结构体变量可以优化成只有结构体名，c++中结构体和class是一致的，默认情况下全是public成员，而class默认情况下全是private
        localtime_r(&ccur,&cur_time);//获得当前时间戳并保存在cur_time中
        char timebuffer[128];
        snprintf(timebuffer,sizeof(timebuffer),"%04d-%02d-%02d %d:%02d:%02d",
                    cur_time.tm_year + 1970,
                    cur_time.tm_mon+1,
                    cur_time.tm_mday,
                    cur_time.tm_hour,
                    cur_time.tm_min,
                    cur_time.tm_sec);
        return timebuffer;
    }

    //1.生成日志 2.根据不同策略打印日志
    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>(); //创建一个智能指针，类似new，但是更安全，c++14引入的标准
        }
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }

        class LogMessage //内部类  1. 内部类默认是外部类的友元类 注：内部类在实例化外部类对象后，可以通过该对象使用外部类的私有成员
                         //       2. 外部类可以任意使用内部类的私有成员和函数
        {
        public:
            LogMessage(LogLevel& level,std::string& src,int line,Logger& logger)
                :_level(level),
                _src(src),
                _line(line),
                _logger(logger),
                _pid(getpid()),
                _cur_time(GetTimeStamp())
            {
                std::stringstream ss;
                ss << "[" << _cur_time << "] "
                   << "[" << LevelToStr(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _src << "] "
                   << "[" << _line << "] "
                   << "- ";
                _loginfo = ss.str();
            }
            template <class T>
            LogMessage& operator<<(const T& info) //此处返回的就是对象本身，所以可以用引用返回，若是临时变量则不能用引用返回
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if(_logger._fflush_strategy)
                    _logger._fflush_strategy->SyncLog(_loginfo);
            }

        private:
            pid_t _pid;
            std::string _loginfo;
            LogLevel _level;
            int _line;
            std::string _src;
            Logger& _logger;
            std::string _cur_time;
        };

        LogMessage operator()(LogLevel level,std::string src,int line)
        {
            return LogMessage(level,src,line,*this);
        }

        ~Logger(){}
    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    Logger logger;//实例化对象 logger

    #define LOG(level) logger(level,__FILE__,__LINE__) //宏定义允许一个参数
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()
}

